package com.www.applyword.http;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.www.applyword.Constants.Constants;
import com.www.applyword.main.LoginActivity;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;
import com.www.applyword.view.CustomLoadingDialog;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.security.SecureRandom;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/3/1.
 */
public class HttpClient {
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static BasicParamsInterceptor basicParamsInterceptor;
    private static final String RET_CODE = "Status";
    private static final String RET_CODE2 = "code";
    private static final String MESSAGE = "Message";
    private static final String MESSAGE2 = "msg";
    private static final String RESULT = "Result";
    private static final String RESULT2 = "data";

    private static int errCode;
    private static int errCode2 = 0;
    private static int type;
    private static Handler handler = new Handler(Looper.getMainLooper());
    private static  HttpClient httpClient;
    private static OkHttpClient okHttpClient;
    private static String path_url;
  /*  public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
          //  .addInterceptor(basicParamsInterceptor) // 添加公共参数拦截器
            .addInterceptor(new LoggingInterceptor()) //添加okhttp日志拦截器
            .sslSocketFactory(createSSLSocketFactory())//创建一个证书对象
            .hostnameVerifier(new TrustAllHostnameVerifier())//校验名称,这个对象就是信任所有的主机,也就是信任所有https的请求
            .connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
            .writeTimeout(20, TimeUnit.SECONDS) //读取超时时间
            .readTimeout(20, TimeUnit.SECONDS) ////写入超时时间
            .retryOnConnectionFailure(false)//连接不上是否重连,false不重连
            .build();*/
    private static Request request;


    public static synchronized OkHttpClient getInstance(){
        if(okHttpClient == null){
            okHttpClient = new OkHttpClient.Builder()
                    //  .addInterceptor(basicParamsInterceptor) // 添加公共参数拦截器
                    .addInterceptor(new LoggingInterceptor()) //添加okhttp日志拦截器
                    // .sslSocketFactory(createSSLSocketFactory())//创建一个证书对象
                    // .hostnameVerifier(new TrustAllHostnameVerifier())//校验名称,这个对象就是信任所有的主机,也就是信任所有https的请求
                    .connectTimeout(20, TimeUnit.SECONDS) //连接超时时间
                    .writeTimeout(20, TimeUnit.SECONDS) //读取超时时间
                    .readTimeout(20, TimeUnit.SECONDS) ////写入超时时间
                    .retryOnConnectionFailure(false)//连接不上是否重连,false不重连
                    .proxy(Proxy.NO_PROXY)
                    .build();
        }
        return okHttpClient;
    }


    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null,  new TrustManager[] { new TrustAllCerts() }, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }


    public static void postImg(final Context context, String url, File file, final CallBack callBack) {
        CustomLoadingDialog.show(context);
        path_url = url;
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("multipartFiles", file.getName(),
                        RequestBody.create(MediaType.parse("image/png"), file));

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                type = 0;
                handlerResponse(context,response, callBack);
            }
        });
    }


    public static void postVideo(final Context context, String url, File file, final CallBack callBack) {
        CustomLoadingDialog.show(context);
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("videoFile", file.getName(),
                        RequestBody.create(MediaType.parse("video/mp4"), file));

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                type = 0;
                handlerResponse(context,response, callBack);
            }
        });
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public  static void post2(final Context context, String url, Map<String, Object> params, final CallBack callBack) {
        CustomLoadingDialog.show(context);
        path_url = url;
      /*  FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            if (map.getValue() == null) {
                value = "";
            } else {
                value = (String) map.getValue();
            }
            builder.add(key, value);
        }*/

        //表单提交 和 json 提交
        Gson gson = new Gson();
        String param = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(JSON, param);

        Logger.json(new Gson().toJson(params));

        //  RequestBody requestBody = builder.build();

        Logger.json(new Gson().toJson(params));
        request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();


        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(context,response, callBack);
            }
        });
    }



    public  static void post(final Context context, String url, Map<String, Object> params, final CallBack callBack) {
        if (!Utils.isNetWorkConnected(context)) {
            Utils.showToastSafe("请检查网络连接");
            return;
        }
        CustomLoadingDialog.show(context);
        path_url = url;
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            if (map.getValue() == null) {
                value = "";
            } else {
                value = (String) map.getValue();
            }
            builder.add(key, value);
        }

        RequestBody requestBody = builder.build();

         Logger.json(new Gson().toJson(params));
            request = new Request.Builder()
                    .tag(context)
                    .url(url)
                    .post(requestBody)
                    .build();


        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (path_url.contains("api.qtshe.com")){
                    handlerResponse2(context,response, callBack);
                }else {
                    handlerResponse(context,response, callBack);
                }
            }
        });
    }



    public static void get(final Context context,String url, Map<String, Object> map, final CallBack callBack) {
        if (!Utils.isNetWorkConnected(Utils.getContext())) {
            Utils.showToastSafe("请检查网络连接");
            return;
        }

        path_url = url;
        CustomLoadingDialog.show(context);
        if (map != null && map.size() >0) {
            url += "?";
            for (String key : map.keySet()) {
                String value = (String) map.get(key);
                url += key + "=" + value + "&";
            }
            url = url.substring(0, url.length() - 1);
        }

        // 去掉最后一个空格
        Logger.json(new Gson().toJson(map));
        Request request = new Request.Builder()
//                .tag(tag)
                .url(url)
             //   .addHeader("Connection", "keep-alive")
                .addHeader("Connection", "close")
                .build();
        String finalUrl = url;
        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                      //  callBack.onFailure(-1, e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                handlerResponse(context,response, callBack);
               /* if (finalUrl.contains(Constants.BAIDU)) {
                    handlerResponse2(context, response, callBack);
                }else {
                    handlerResponse(context, response, callBack);
                }*/
            }
        });
    }

    private static void handlerResponse2(final Context context, Response response, final CallBack callBack) throws IOException {
        //看清楚是response.body().string()不是response.body().toString()
        String json = response.body().string();
        //json = json.replace("null", "\"\"");
        Logger.json(json);
        System.out.println("json==" + json);
        final String finalJson = json;
        handler.post(new Runnable() {  //更新UI
            @Override
            public void run() {
                try {

                    JSONObject jsonObject = new JSONObject(finalJson);
                    int errCode = jsonObject.getInt(RET_CODE2);

                    if (errCode == 4000) {
                        if (finalJson.contains(RESULT2)) {
                            String data = jsonObject.getString(RESULT2);
                            callBack.onSuccess(new Gson().fromJson(data, callBack.type));
                        } else {
                            callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));
                        }
                    }
                    String msg = jsonObject.getString(MESSAGE2);
                    //Utils.showToastSafe(msg);
                    CustomLoadingDialog.dismiss(context);
                } catch (Exception e) {
                    e.printStackTrace();
                    callBack.onFailure(-1, e.getLocalizedMessage());
                   /* if (!TextUtils.isEmpty(e.getLocalizedMessage()))
                        if (e.getLocalizedMessage().contains("<html><head><title>")) {
                            UIUtils.showToastSafe("数据加载错误");
                        }*/
                    CustomLoadingDialog.dismiss(context);
                }
            }
        });
    }

    /**
     * 根据tag取消请求
     *
     * @param tag 标签
     */
    public static void cancelRequest(Object tag) {
        for (Call call : getInstance().dispatcher().queuedCalls()) {
            if (call.request().tag().equals(tag)) {
                call.cancel();
            }
        }
    }


    private static void handlerResponse(Context context, Response response, final CallBack callBack) throws IOException {
        //看清楚是response.body().string()不是response.body().toString()
        String json = response.body().string();
       // json = json.replace("null", "\"\"");
        Logger.json(json);
        System.out.println("json==" + json);
        final String finalJson = json;
        handler.post(new Runnable() {   //子线程耗时操作
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(finalJson);
                    int errCode = jsonObject.getInt(RET_CODE);

                    String className = context.getClass().getSimpleName();

                    //  int errCode;
                    if (className.equals("RechargeActivity") || className.equals("CodeActivity")) {
                        callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));
                        CustomLoadingDialog.dismiss(context);
                        return;
                    }

                    if (errCode == 1) {
                        if (finalJson.contains(RESULT)) {
                            String data = jsonObject.getString(RESULT);
                            if (finalJson.contains(MESSAGE)) {
                                String msg = jsonObject.getString(MESSAGE);
                            }

                            if (path_url.equals(Constants.GETALLCITY)){
                                SPUtil.put("json",data);
                            }

                            callBack.onSuccess(new Gson().fromJson(data, callBack.type));
                        } else {
                            callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));
                        }
                    } else if (errCode == 9) {  //NEED_LOGIN
                        Intent intent = new Intent(Utils.getContext(), LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        Utils.getContext().startActivity(intent);
                    } else if (errCode == 3){  //余额不足
                        if (!finalJson.contains(MESSAGE)) return;
                        String msg = jsonObject.getString(MESSAGE);
                        Utils.showToastSafe(msg);
                    }else {
                        if (!finalJson.contains(MESSAGE)) return;
                        String msg = jsonObject.getString(MESSAGE);
                        if (msg.equals("圈闭余额不足") || msg.equals("支付密码错误") || msg.contains("用户已注册")) {
                            callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));
                        } else {
                          //  if (!msg.contains("当前简历已收藏"))
                           // Utils.showToastSafe(msg);
                        }
                    }

                    CustomLoadingDialog.dismiss(context);

                } catch (Exception e) {
                    e.printStackTrace();
                    callBack.onFailure(-1, e.getLocalizedMessage());
                    CustomLoadingDialog.dismiss(Utils.getContext());
                }
            }
        });
    }

    /**
     * 请求响应日志信息，方便debug
     */
    public static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            Logger.i(String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));
            if (null != chain) {
                Response response = chain.proceed(request);
                long t2 = System.nanoTime();

                Logger.i(String.format("Received response for %s in %.1fms%n%s",
                        response.request().url(), (t2 - t1) / 1e6d, response.headers()));
                return response;
            }
            return null;
        }
    }
}
